const app = getApp();

Page({
  data: {
    categories: [],
    currentCategory: null,
    products: [],
    loading: false,
    page: 1,
    hasMore: true
  },

  onLoad(options) {
    this.loadCategories(options.id);
  },

  async loadCategories(selectedId) {
    try {
      const res = await app.request({
        url: '/product/categories/',
        method: 'GET'
      });

      console.log('分类数据：', res); // 添加日志

      // 确保返回的数据是数组
      const categories = Array.isArray(res.data) ? res.data : (Array.isArray(res) ? res : []);
      
      if (categories.length === 0) {
        this.setData({
          categories: [],
          currentCategory: null
        });
        return;
      }
      
      // 添加默认图标
      const categoriesWithIcon = categories.map(item => ({
        ...item,
        icon: item.icon || '/assets/images/default-category.png'
      }));

      // 如果有选中的分类ID，就选中对应分类，否则选中第一个
      const currentCategory = selectedId 
        ? categoriesWithIcon.find(c => c.id === parseInt(selectedId)) || categoriesWithIcon[0]
        : categoriesWithIcon[0];

      this.setData({ 
        categories: categoriesWithIcon,
        currentCategory
      }, () => {
        if (this.data.currentCategory) {
          this.loadProducts();
        }
      });
    } catch (error) {
      console.error('获取分类列表失败', error);
      wx.showToast({
        title: '获取分类失败',
        icon: 'none'
      });
      this.setData({
        categories: [],
        currentCategory: null
      });
    }
  },

  handleCategoryTap(e) {
    const { id } = e.currentTarget.dataset;
    const category = this.data.categories.find(c => c.id === parseInt(id));
    if (category && (!this.data.currentCategory || category.id !== this.data.currentCategory.id)) {
      this.setData({
        currentCategory: category,
        products: [],
        page: 1,
        hasMore: true
      }, () => {
        this.loadProducts();
      });
    }
  },

  async loadProducts() {
    if (this.data.loading || !this.data.hasMore || !this.data.currentCategory) return;

    this.setData({ loading: true });

    try {
      const res = await app.request({
        url: '/product/products/',
        method: 'GET',
        data: {
          category_id: this.data.currentCategory.id,
          page: this.data.page,
          page_size: 10
        }
      });

      console.log('商品数据：', res); // 添加日志

      // 确保返回的数据是数组
      const products = Array.isArray(res.data.results) ? res.data.results : [];
      const currentProducts = this.data.products;

      this.setData({
        products: [...currentProducts, ...products],
        hasMore: products.length === 10,  // 如果返回10条数据，说明可能还有更多
        page: this.data.page + 1,
        loading: false
      });
    } catch (error) {
      console.error('获取商品列表失败', error);
      wx.showToast({
        title: '获取商品失败',
        icon: 'none'
      });
      this.setData({ 
        loading: false,
        hasMore: false
      });
    }
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProducts();
    }
  },

  handleProductTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${id}`
    });
  }
}); 